//
//  MineVC.m
//  ImGuider
//
//  Created by 李陆涛 on 2017/12/11.
//  Copyright © 2017年 imguider. All rights reserved.
//

#import "MineVC.h"
#import "UIView+Gradient.h"
#import "AccountCell.h"

#import "ChargeMoneyVC.h"
#import "MessageVC.h"
#import "AccountCouponVC.h"
#import "AccountCollectVC.h"
#import "SDPhotoBrowser.h"
#import "TranslationVC.h"
#import "AccountTicketVC.h"
#import "ADView.h"
@interface MineVC () <SDPhotoBrowserDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (weak, nonatomic) IBOutlet UIView *headView;
@property (weak, nonatomic) IBOutlet UIView *containView;
@property (weak, nonatomic) IBOutlet UIImageView *headImageView;
@property (weak, nonatomic) IBOutlet UILabel *useNameLabel;

@property (weak, nonatomic) IBOutlet UIButton *translationBtn;
@property (weak, nonatomic) IBOutlet UIButton *rateBtn;

@property (weak, nonatomic) IBOutlet UILabel *moneyLabel;
@property (weak, nonatomic) IBOutlet UILabel *msgLabel;
@property (weak, nonatomic) IBOutlet UILabel *couponLabel;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *userNameLabelTop;
@property (weak, nonatomic) IBOutlet UIImageView *modifyImageView;
@property (weak, nonatomic) IBOutlet UILabel *modifyLabel;


@property (weak, nonatomic) IBOutlet UILabel *moneyDesLabel;
@property (weak, nonatomic) IBOutlet UILabel *msgDesLabel;
@property (weak, nonatomic) IBOutlet UILabel *couponDesLabel;

@property (weak, nonatomic) IBOutlet ADView *exchangeView;

@property (weak, nonatomic) IBOutlet ADView *recommendView;

@property (weak, nonatomic) IBOutlet UIView *couponView;
@property (weak, nonatomic) IBOutlet UIView *ticketView;

@property (weak, nonatomic) IBOutlet UILabel *ticketLabel;
@property (weak, nonatomic) IBOutlet UILabel *ticketDesLabel;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *moneyViewW;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *msgViewW;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *couponViewW;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *ticketViewW;


@property (nonatomic, strong) NSArray *dataSource;

@end

@implementation MineVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupUI];
    [self setupData];
    [self closeAutomaticallyAdjustsScrollViewInsets:self.tableView];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloaUserInfoPage) name:kRefreshUserNotif object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginSuccessCallback) name:kLoginSuccessNotif object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadUserData) name:kReloadUserDataNotif object:nil];
}

- (void)setupUI {
    
    [self reloadUserData];
    
    self.couponView.hidden = YES;
    
    self.modifyLabel.text = MYLocalizedString(@"MYINFO_MODIFY_INFO", nil);
    self.moneyDesLabel.text = MYLocalizedString(@"ACCOUNT_WALLET", nil);
    self.msgDesLabel.text = MYLocalizedString(@"ACCOUNT_MESSAGE", nil);
    self.couponDesLabel.text = MYLocalizedString(@"ACCOUNT_VOUCHER", nil);
    
    self.recommendView.text = MYLocalizedString(@"VOUCHER_SHARE_CHARGE", nil);
    self.exchangeView.text = MYLocalizedString(@"VOUCHER_SHARE_EXCHANGE", nil);
    
    [self.rateBtn setTitle:MYLocalizedString(@"EXCHANGE_RATE_RESEARCH", nil) forState:UIControlStateNormal];
    
    self.rateBtn.titleLabel.numberOfLines = 0;
    self.rateBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
    self.translationBtn.titleLabel.numberOfLines = 0;
    self.translationBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
    
    [self.translationBtn setTitle:MYLocalizedString(@"TRANSLATION_NAME", nil) forState:UIControlStateNormal];
    
    self.headImageView.layer.borderWidth = 1.0f;
    self.headImageView.layer.borderColor = kBGColor.CGColor;
    
    self.ticketDesLabel.text = MYLocalizedString(@"TICKET_TITLE", nil);
    
    if ([AppManager sharedManager].hasTicket) {
        
        self.ticketView.hidden = NO;
        
        CGFloat width = kScreenWidth / 4.0f;
        
        CGFloat maxWidth = width * 5 / 4.0f;
        
        CGFloat minWidth = width * 3 / 4.0f;
        
        self.moneyViewW.constant = maxWidth;
        self.msgViewW.constant = minWidth;
        self.couponViewW.constant = maxWidth;
        self.ticketViewW.constant = minWidth;
        
    } else {
        
        self.ticketView.hidden = YES;
        
        CGFloat width = kScreenWidth / 3.0f;
        
        self.moneyViewW.constant = width;
        self.msgViewW.constant = width;
        self.couponViewW.constant = width;
        self.ticketViewW.constant = 0;
    }

    @weakify(self);
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        @strongify(self);
        
        [self reloadUserData];
    }];
    [self.tableView setThemeStyle:ThemeStyleBlack];
}

- (void)setupData {
    
    self.dataSource = @[
                        @[@{@"name":MYLocalizedString(@"ACCOUNT_SUBSCRIPTION", nil), @"class":@"AccountCollectVC",@"type":@"sb",@"params":@{@"type":@(1)}},
                          @{@"name":MYLocalizedString(@"ACCOUNT_FLLOW", nil), @"class":@"AccountCollectVC",@"type":@"sb"},
                          @{@"name":MYLocalizedString(@"ACCOUNT_MY_QUESTION", nil), @"class":@"AccountMyQuestion",@"type":@"sb"},
                          @{@"name":MYLocalizedString(@"ACCOUNT_DOWNLOAD", nil), @"class":@"AllDownloadVC",@"type":@"xib"}],
                        
                        @[ @{@"name":MYLocalizedString(@"SETTING_FEEDBACK", nil), @"class":@"FeedBackVC",@"type":@"sb"},
                           @{@"name":MYLocalizedString(@"SETTING_CONTACT", nil), @"class":@"ContactService",@"type":@"sb"},
                           @{@"name":MYLocalizedString(@"ACCOUNT_SETTING", nil), @"class":@"AccountSettingVC",@"type":@"sb"}],
                        ];
    
    [self reloaUserInfoPage];
}

- (void)reloaUserInfoPage {
    
    
    if (![UserManager sharedManager].token) {
        
        self.useNameLabel.text = [NSString stringWithFormat:@"%@/%@",MYLocalizedString(@"LOGIN_TITLE", nil),MYLocalizedString(@"REGISTER_TITLE", nil)];
        self.moneyLabel.text = @"--";
        self.msgLabel.text = @"--";
        self.couponLabel.text = @"--";
        self.headImageView.image = [UIImage imageNamed:@"default"];
        
        self.couponView.hidden = YES;
        self.modifyLabel.hidden = YES;
        self.modifyImageView.hidden = YES;
        
        if ([AppManager sharedManager].language == AppLanguageItaliano) {
            
            self.userNameLabelTop.constant = 10;
        } else {
            
            self.userNameLabelTop.constant = 30;
        }
        
        self.ticketLabel.text = @"--";

        self.ticketView.hidden = YES;
        
        return;
    }
    
    self.modifyLabel.hidden = NO;
    self.modifyImageView.hidden = NO;
    self.userNameLabelTop.constant = 10;
    
    if ([AppManager sharedManager].hasTicket) {
        
        self.couponView.hidden = NO;
        self.ticketView.hidden = NO;
    } else {
        self.couponView.hidden = YES;
        self.ticketView.hidden = YES;
    }
    
    self.useNameLabel.text = [UserManager sharedManager].user.realname;
    [self.headImageView setImageURL:[NSURL URLWithString:[UserManager sharedManager].user.headimg] placeholderImage:[UIImage imageNamed:@"default"]];
    
    self.moneyLabel.text = @([UserManager sharedManager].user.coin).stringValue;
    self.msgLabel.text = @([UserManager sharedManager].user.messages).stringValue;
    self.couponLabel.text = @([UserManager sharedManager].user.coupons).stringValue;
    
    self.ticketLabel.text = @([UserManager sharedManager].user.tickets).stringValue;
}
- (IBAction)showBigImageView:(id)sender {
    
    if (![IGUtil hasLoginOrPresentLogin]) {
        return;
    }
    
    SDPhotoBrowser *browser = [SDPhotoBrowser new];
    browser.sourceImagesContainerView = self.headImageView;
    browser.imageCount = 1;
    browser.currentImageIndex = 0;
    browser.delegate = self;
    //    browser.type = 2;
    [browser show];
}

//0语音翻译；1汇率查询

- (IBAction)funDetail:(UIButton *)sender {
    
    NSInteger tag = sender.tag;
    
    switch (tag) {
            
        case 0:{//语音翻译
            
            if (@available(iOS 10.0, *)) {
                TranslationVC * vc = [[TranslationVC alloc] init];
                
                vc.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:vc animated:YES];
                
            } else {
                
                [IGUtil showToast:@"当前系统版本暂不支持"];
            }
            
        }
            break;
        case 1:{//汇率查询
            
            UIViewController *accVC = [IGUtil loadViewController:@"RateQueryVC" storyboard:@"Account"];
            accVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:accVC animated:YES];
        }
            break;
        default:
            break;
    }
}

//0用户信息；1钱包；2消息；3优惠券；4门票
- (IBAction)showDetail:(UITapGestureRecognizer *)sender {
    
    if (![IGUtil hasLoginOrPresentLogin]) {
        
        return;
    }
    
    NSInteger tag = sender.view.tag;
    
    switch (tag) {
        case 0:{
            
            UIViewController *accVC = [IGUtil loadViewController:@"AccountUserinfoVC" storyboard:@"Account"];
            accVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:accVC animated:YES];
        }
            break;
        case 1:{
            
            UIViewController *moneyVC = [IGUtil loadViewController:@"ChargeMoneyVC" storyboard:@"Account"];
            moneyVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:moneyVC animated:YES];
        }
            break;
        case 2:{
            
            MessageVC *vc = [[MessageVC alloc] initWithStyle:UITableViewStyleGrouped];
            vc.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:vc animated:YES];
        }
            break;
        case 3:{
            
            AccountCouponVC *ticketVC = [IGUtil loadViewController:@"AccountCouponVC" storyboard:@"Account"];
            ticketVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:ticketVC animated:YES];
        }
            break;
            
        case 4:{
            
            AccountTicketVC *ticketVC = [IGUtil loadViewController:@"AccountTicketVC" storyboard:@"Account"];
            ticketVC.hidesBottomBarWhenPushed = YES;
            [self.navigationController pushViewController:ticketVC animated:YES];
        }
            break;
            
        default:
            break;
    }
    
}

- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


#pragma mark-UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return self.dataSource.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    NSArray *dataSource = self.dataSource[section];
    
    return dataSource.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSArray *dataSource = self.dataSource[indexPath.section];
    NSDictionary *dict = dataSource[indexPath.row];
    
    AccountCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    [cell configWithDict:dict];
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.section == 0 && ![IGUtil hasLoginOrPresentLogin]) { // 我的相关
        
        return;
    }
    
    NSArray *dataSource = self.dataSource[indexPath.section];
    NSDictionary *dict = dataSource[indexPath.row];
    
    UIViewController *accVC = [self getClassName:dict[@"class"] type:dict[@"type"]];
    
    if (!accVC) {
        return;
    }
    
    NSDictionary *params = dict[@"params"];
    
    for (NSString *key in params.allKeys) {
        
        id value = params[key];
        
        [accVC setValue:value forKey:key];
    }
    
    accVC.hidesBottomBarWhenPushed = YES;
    
    [self.navigationController pushViewController:accVC animated:YES];
}

- (id)getClassName:(NSString *)name type:(NSString *)type {
    
    UIViewController *vc = nil;
    
    if ([type isEqualToString:@"sb"]) {
        
        vc = [IGUtil loadViewController:name storyboard:@"Account"];
    } else {
        
        vc = [NSClassFromString(name) new];
    }
    
    return vc;
}

- (IBAction)loginAction:(id)sender {
    
    [IGUtil hasLoginOrPresentLogin];
}

- (void)loginSuccessCallback {
    
    [self reloaUserInfoPage];
    
    [self reloadUserData];
}

- (void)reloadUserData {
    
    if ([UserManager sharedManager].token) {
        
        @weakify(self);
        [NetAPIManager getUserInfoWithBlock:^(NSString *result, NSError *error) {
            @strongify(self);
            [self.tableView.mj_header endRefreshing];
            [self reloaUserInfoPage];
        }];
        
    } else {
        
        [self.tableView.mj_header endRefreshing];
    }
}

- (UIImage *)photoBrowser:(SDPhotoBrowser *)browser placeholderImageForIndex:(NSInteger)index {
    
    return self.headImageView.image;
}
- (NSURL *)photoBrowser:(SDPhotoBrowser *)browser highQualityImageURLForIndex:(NSInteger)index {
    
    return [NSURL URLWithString:[UserManager sharedManager].user.headimg];
}

@end

